package cn.wjssl.domain.strategy.service.rule.chain.impl;

import cn.wjssl.domain.strategy.model.entity.StrategyAwardEntity;
import cn.wjssl.domain.strategy.repository.IStrategyRepository;
import cn.wjssl.domain.strategy.service.armory.IStrategyDispatch;
import cn.wjssl.domain.strategy.service.rule.chain.AbstractLogicChain;
import cn.wjssl.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import cn.wjssl.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author：lxd
 * @Description 权重抽奖方式
 * @Date：2025/2/10
 */

@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;

    @Resource
    private IStrategyDispatch dispatch;

    @Override
    protected String currentRuleModel() {
        return DefaultChainFactory.LogicModel.RULE_WEIGHT.getCode();
    }

    /**
     * 权重规则过滤；
     * 1. 权重规则格式；4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
     * 2. 解析数据格式；判断哪个范围符合用户的特定抽奖范围
     * @param userId     用户ID
     * @param strategyId 策略ID
     * @return 责任链奖品流转对象
     */
    @Override
    public DefaultChainFactory.StrategyAwardVO logicChain(String userId, Long strategyId) {
        log.info("抽奖责任链-权重开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, currentRuleModel());

        // 获取 rule_value
        String ruleValue = repository.queryStrategyRuleValue(strategyId, currentRuleModel(), null);
        // 转换成map [{4000,"4000:102, 103, 104, 105"},{5000,"5000:102, 103, 104, 105, 106"} ...]
        Map<Long, String> ruleValueMap = ruleValue2Map(ruleValue);
        // 如果没有分配权重值, 那就返回null
        if (null == ruleValueMap || ruleValueMap.isEmpty()) return null;
        // 如果有, 比较用户积分和权重值
        List<Long> weightValues = new ArrayList<>(ruleValueMap.keySet());
        Collections.sort(weightValues);

        // 查询用户当前抽奖次数
        Integer userScore = repository.queryActivityAccountTotalUseCount(userId, strategyId);

        // 用户当前处在哪个权重
        Long currectWeightValue = weightValues.stream()
                .sorted(Comparator.reverseOrder())
                .filter(weightValue -> userScore >= weightValue)
                .findFirst()
                .orElse(null);
        // 如果处于权重内 那就返回权重抽奖Id
        if (currectWeightValue != null) {
            Integer awardId = dispatch.getRandomAwardId(strategyId, ruleValueMap.get(currectWeightValue));
            StrategyAwardEntity strategyAwardEntity = repository.queryStrategyAwardEntity(strategyId, awardId);
            log.info("抽奖责任链-权重接管 userId: {} strategyId: {} ruleModel: {} awardId: {}", userId, strategyId, currentRuleModel(), awardId);
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .awardTitle(strategyAwardEntity.getAwardTitle())
                    .sort(strategyAwardEntity.getSort())
                    .awardConfig(strategyAwardEntity.getRuleModels())
                    .logicModel(currentRuleModel())
                    .build();
        }
        // 不处于权重内, 进行下一个过滤器的过滤方法
        log.info("抽奖责任链-权重放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, currentRuleModel());
        return next().logicChain(userId, strategyId);
    }

    // 对 rule_value 进行解析, 存为map
    // map应该是 [{4000,"4000:102, 103, 104, 105"},{5000,"5000:102, 103, 104, 105, 106"} ...]
    private Map<Long, String> ruleValue2Map(String ruleValue) {
        Map<Long, String> ruleValueMap = new HashMap<>();
        // 先按空格分割
        String[] ruleValueSplits = ruleValue.split(Constants.SPACE);
        // 再按冒号分割, 获取权重值
        for (String ruleValueKey : ruleValueSplits) {
            // 检查输入是否为空
            if (ruleValueKey == null || ruleValueKey.isEmpty()) {
                return ruleValueMap;
            }
            String[] parts = ruleValueKey.split(Constants.COLON);
            // 如果不是 xx:xx 格式 ,就报异常
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
            }
            ruleValueMap.put(Long.parseLong(parts[0]), ruleValueKey);
        }
        return ruleValueMap;
    }
}
